package com.thinvent.recommend.manager.manager.impl;

import com.thinvent.recommend.manager.manager.DocumentSearchManager;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.similarities.ClassicSimilarity;
import org.apache.lucene.store.Directory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 基于 Lucene TF–IDF 的文档检索管理器实现
 */
@Service
public class DocumentSearchManagerImpl implements DocumentSearchManager {

    @Autowired
    private Directory directory;         // 在 LuceneConfig 中注入的索引目录

    @Autowired
    private Analyzer jiebaAnalyzer;      // 自定义的 JiebaAnalyzer

    @Override
    public List<String> searchByTfIdf(String queryText, int topK) throws Exception {
        try (DirectoryReader reader = DirectoryReader.open(directory)) {
            IndexSearcher searcher = new IndexSearcher(reader);
            // 使用经典的 TF–IDF 模型计算相似度
            searcher.setSimilarity(new ClassicSimilarity());

            // 用 JiebaAnalyzer 分词并解析查询
            QueryParser parser = new QueryParser("content", jiebaAnalyzer);
            Query query = parser.parse(QueryParser.escape(queryText));

            TopDocs topDocs = searcher.search(query, topK);
            List<String> ids = new ArrayList<>(topDocs.scoreDocs.length);
            for (ScoreDoc sd : topDocs.scoreDocs) {
                Document d = searcher.doc(sd.doc);
                ids.add(d.get("id"));
            }
            return ids;
        }
    }
}
